<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>defineProperty</h1>

    <h2 id="define-property"></h2>
    <input placeholder="请输入" onkeyup="msgChange(this)" />
    <input placeholder="请输入" onkeyup="numChange(this)" />
    <script>
        let data = {
            msg: "",
            num: 0,
        };

        let vm = {};

        Object.keys(data).forEach((key) => {
            // 数据劫持
            Object.defineProperty(vm, key, {
                // 可枚举，可遍历
                enumerable: true,
                // 可配置（可以用delete删除，可以用defineProperty重新定义）
                configurable: true,
                get() {
                    return data[key];
                },
                set(val) {
                    if (val === data[key]) return;

                    data[key] = val;
                    document.querySelector(
                        "#define-property"
                    ).innerHTML = val;
                },
            });
        });
        
        function msgChange(e) { 
            vm.msg = e.value 
        }
        function numChange(e) { 
            vm.num = e.value 
        }
    </script>
</body>

</html>